import axios from 'axios'
import router from '../router'
import {rabbitmqAuth} from "../stores/counter.js";
import {ElMessage} from 'element-plus'

// create an axios instance
const service = axios.create({
    // baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
    baseURL: '', // url = base url + request url
    withCredentials: true, // send cookies when cross-domain requests
    timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
    config => {
        config.headers.Authorization = rabbitmqAuth().basic
        return config
    },
    error => {
        return Promise.reject(error)
    }
)

// response interceptor
service.interceptors.response.use(
    response => {
        return response.data
    },
    error => {
        console.log(error)
        if (error.response.status === 401) {
            ElMessage({
                message: '未登录或登陆失效',
                type: 'warning',
            })
            router.push({path: 'login'})
        }
        if (error.response.status === 500) {
            ElMessage({
                message: '连接失败',
                type: 'warning',
            })
        } else {
            ElMessage({
                message: error.response.data.reason,
                type: 'warning',
            })
        }
        return Promise.reject(error)
    }
)

export default service
